package controller

import (
	"context"
	"github.com/gin-gonic/gin"
	"goproject/commonType"
	"goproject/faultHandler"
	"goproject/k8s"
	"goproject/logger"
)

type testFault struct {
	FaultConfig commonType.Fault `json:"fault_config"`
	Namespace   string           `json:"namespace"`
	PodName     string           `json:"podname"`
}

func InjectFault(c *gin.Context) {
	log := logger.GetLogger()
	k8s.Init()
	// 从body获取数据
	var testFault testFault
	if err := c.ShouldBindJSON(&testFault); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	// 调用faultHandler包下的InjectFault函数
	chaos, err := faultHandler.InjectFault(context.Background(), testFault.FaultConfig, testFault.PodName, testFault.Namespace)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	// 查看故障状态
	chaosStatus := k8s.GetChaosStatus(chaos)
	k8s.RecoverFromChaos(chaos)
	k8s.WaitUntilInChaos(testFault.PodName, chaos)
	log.Infof("故障状态: %v", chaosStatus)

	c.JSON(200, gin.H{"message": "fault injected successfully"})
}
